/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assisisw.smartcal.webuisubsystem.managedbean.validator;

import assisisw.smartcal.entitysubsystem.Calendar;
import assisisw.smartcal.entitysubsystem.User;
import assisisw.smartcal.securitysubsystem.IMailVerifier;
import java.io.Serializable;
import java.util.Objects;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Francesco
 */
public class EditCalendarSharingValidator implements Validator , Serializable
{

    // Static Fields
    
    /***/
    private static final FacesMessage requiredMessage = new FacesMessage ( "You can not share with no one !" ) ;
    
    /***/
    private static final FacesMessage alreadySharedWithHimMessage = new FacesMessage ( "You've alredy shared this calendar with him." ) ;
    
    // Instance Fields
    
    /***/
    @EJB ()
    private IMailVerifier mailVerifier ;
    
    /***/
    private Calendar calendar ;
    
    // Instance Methods
    
    /**
     * AS THE SUPER'S ONE.
     */
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
    {
        String mail ;
        if ( Objects.nonNull ( value ) && ! value.toString ().isEmpty () )
        {
            mail = value.toString () ;
            if ( ! isAlreadyShared ( mail ) )
            {
                // is the mail valid ?
                if ( ! ( mailVerifier.isStaticallyOk ( mail ) && mailVerifier.exists ( mail ) ) )
                    throw new ValidatorException ( new FacesMessage ( "Not a valid mail !" ) ) ;
            }
            else
                throw new ValidatorException ( alreadySharedWithHimMessage ) ;
        }
        else
            throw new ValidatorException ( requiredMessage ) ;
    }
    
    /***/
    public void setCalendar ( Calendar calendar ) 
    {
        this.calendar = calendar ;
    }
    
    private boolean isAlreadyShared ( String mail ) 
    {
        boolean res ;
        res = false ;
        for ( User u : calendar.getPeopleWhoCanAccess() )
            if ( u.getMail().compareToIgnoreCase ( mail ) == 0 )
            {
                res = true ;
                break ;
            }
        return res ;
    }
    
}
